/**
 * 
 */
package com.contact.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.contact.dao.ContactDao;
import com.contact.dao.MessageDao;
import com.contact.model.Contact;
import com.contact.model.Message;

/**
 * @author David Zheng
 *
 */
public class ContactServiceImpl implements ContactService {
	
	private ContactDao contactDao;
	
	private MessageDao messageDao;
	
	private static List<String> aliasList = new ArrayList<String>(); 
	
	public void initCache() {
		for (Contact contact : this.loadAll()) {
			aliasList.add(contact.getAlias());
		}	
	}
	
	public Contact loadById(int id) {
		return contactDao.loadById(id);
	}
		

	/* (non-Javadoc)
	 * @see com.contact.service.ContactService#insertMessage(String content)
	 */
	@Override
	public void insertMessage(String content) {
		Message msg = new Message();
		msg.setCreateDate(new Date(System.currentTimeMillis()));
		msg.setContent(content);
		messageDao.insertMessage(msg);		
	}

	/* (non-Javadoc)
	 * @see com.contact.service.ContactService#loadMessages()
	 */
	@Override
	public List<Message> loadMessages() {
		return messageDao.loadMessages();		
	}

	/* (non-Javadoc)
	 * @see com.contact.service.ContactService#load(java.lang.String)
	 */
	public List<Contact> load(String name) {
		// TODO Auto-generated method stub
		return contactDao.load(name);
	}

	/* (non-Javadoc)
	 * @see com.contact.service.ContactService#loadAll()
	 */
	public List<Contact> loadAll() {
		// TODO Auto-generated method stub
		return contactDao.loadAllValidContacts();
	}

	/**
	 * @param contactDao the contactDao to set
	 */
	public void setContactDao(ContactDao contactDao) {
		this.contactDao = contactDao;
	}
	
	public List<String> getAliasListCache() {
				
		return aliasList;
	}		
	
	/**
	 * @param messageDao the messageDao to set
	 */
	public void setMessageDao(MessageDao messageDao) {
		this.messageDao = messageDao;
	}

	public List<String> search(String name, List<String> list, int limit) {
		List<String> results = new ArrayList<String>();
		Pattern pattern = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
		for (int i = 0, j = 0; i < list.size(); i++) {
			Matcher matcher = pattern.matcher(list.get(i));
			if (matcher.find()) {
				results.add(list.get(i));
				if (++j >= limit) break;
			}
		}
		return results;
	}
	
}
